import axios from "axios";
import Qs from "qs";
import { message } from "antd";
import { apiHost } from "./config";
import history from "../util/history";
import store from "../store";

const reqBefore = async () => {
  // axios 请求全局拦截
  axios.interceptors.request.use(
    config => {
      //请求发送之前
      if (
        config.headers["Content-Type"] === "application/x-www-form-urlencoded"
      ) {
        config.data = Qs.stringify(config.data);
      }
      return config;
    },
    function(error) {
      // 请求错误
      return Promise.reject(error);
    }
  );
};
const resBefore = async () => {
  // 添加一个返回拦截器
  axios.interceptors.response.use(
    res => {
      if (res.data.code === 999) {
        message.warning(res.data.msg);
        setTimeout(() => {
          history.push(`/login`, {
            fromPath: history.location.pathname
          });
        }, 1500);
      } else if (res.data.code !== 200) {
        message.warning(res.data.msg);
      }
      return res;
    },
    err => {
      // 对返回的错误进行一些处理
      if (err && err.response) {
        switch (err.response.status) {
          case 400:
            err.message = "请求错误";
            break;

          case 401:
            err.message = "未授权，请登录";
            break;

          case 403:
            err.message = "拒绝访问";
            break;

          case 404:
            err.message = `请求地址出错: ${err.response.config.url}`;
            break;

          case 408:
            err.message = "请求超时";
            break;

          case 500:
            err.message = "服务器内部错误";
            break;

          case 501:
            err.message = "服务未实现";
            break;

          case 502:
            err.message = "网关错误";
            break;

          case 503:
            err.message = "服务不可用";
            break;

          case 504:
            err.message = "网关超时";
            break;

          case 505:
            err.message = "HTTP版本不受支持";
            break;

          default:
        }
      }
      return Promise.reject(err);
    }
  );
};
// 请求拦截
reqBefore();
//响应拦截
resBefore();
const getData = async option => {
  const type = option.type;
  const url = apiHost + option.url;
  const data = option.data || {};
  const headers = Object.assign(
    {
      token: store.getState().token || ""
    },
    option.headers || {}
  );
  return axios({
    method: type,
    url: url,
    timeout: 60000,
    headers: headers,
    data: type === "post" ? data : {},
    params: type === "get" ? data : {}
  });
};

const $post = async option => {
  option.type = "post";
  let res = await getData(option);
  return res && res.data ? res.data : res;
};
const $get = async option => {
  option.type = "get";
  let res = await getData(option);
  return res && res.data ? res.data : res;
};

const $httpAll = async (allRequst, callback) => {
  axios.all(allRequst).then(
    axios.spread(function() {
      callback(...arguments);
    })
  );
};

export { getData, $post, $get, $httpAll };
